package com.woniuxy.access.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.woniuxy.access.config.MQConstant;
import com.woniuxy.access.entity.TradeLog;
import com.woniuxy.access.service.ITradeLogService;
import com.woniuxy.common.model.dto.bank.BankCardAddDTO;
import com.woniuxy.common.model.dto.bank.BankCardRequestDto;
import com.woniuxy.common.model.dto.bank.BaseResult;
import com.woniuxy.common.model.dto.bank.SignatureDto;
import com.woniuxy.common.model.vo.trade.BorrowSyncRecordVo;
import com.woniuxy.common.result.Result;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * <p>
 * 托管系统交易记录表 前端控制器
 * </p>
 *
 * @author yellow docker
 * @since 2025-03-20
 */
@Slf4j
@RestController
@RequestMapping("/trade-log")
public class TradeLogController {

    @Autowired
    private ITradeLogService tradeLogService;

    /**
     * 绑卡
     */
    @PostMapping("/bank/access/card")
    public SignatureDto proxyBindCardLog(@RequestBody BankCardAddDTO bankCardAddDTO) {
        SignatureDto signatureDto = tradeLogService.proxyBindCardLog(bankCardAddDTO);
        return signatureDto;
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 模拟 银行托管系统回调接口
     */
    @PostMapping("/bank/access/receive")
    public String callbackUpdate(@RequestBody BankCardRequestDto bankCardRequestDto) {
        // 根据流水号，修改交易记录的同步状态:synchronize_status
        // 更新tradelog 中的 日志:  synchronize_status\confirmdata
        tradeLogService.update(Wrappers.lambdaUpdate(TradeLog.class)
                .set(TradeLog::getSynchronizeStatus,1)
                .set(TradeLog::getConfirmDate,new Date())
                .eq(TradeLog::getReqCode,bankCardRequestDto.getReqCode())
        );
        // 发送MQ消息，通知系统管理服务绑卡结果
        rabbitTemplate.convertAndSend(
                MQConstant.SDDFP_EXCHANGE_BIND, //交换机
                MQConstant.BIND_CARD_MESSAGE,   //路由
                bankCardRequestDto);

        return "ok";
    }

    //记录 借款审核 的日志操作
    @ApiOperation("借款记录审核，同步数据")
    @PostMapping("/bank/access/sync/borrow")
    public Result<BaseResult> syncBorrowRecord(@RequestBody BorrowSyncRecordVo borrowSyncRecordVo) {
        log.info("trade 平台 发送数据:{}",borrowSyncRecordVo);
        Result<BaseResult> result = tradeLogService.syncBorrowRecord(borrowSyncRecordVo);
        return result;
    }

}
